package com.sy.musicapp

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.runtime.*
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.insets.ProvideWindowInsets
import com.google.accompanist.insets.systemBarsPadding
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.sy.musicapp.model.*
import com.sy.musicapp.service.MediaPlayerService
import com.sy.musicapp.ui.common.NavEnterAndExitAnimation
import com.sy.musicapp.ui.common.navigate
import com.sy.musicapp.ui.home.HomeScreen
import com.sy.musicapp.ui.home.LittlePlayControl
import com.sy.musicapp.ui.home.MusicListDrawer
import com.sy.musicapp.ui.login.LoginScreen
import com.sy.musicapp.ui.play.PlayScreen
import com.sy.musicapp.ui.playlist.PlaylistScreen
import com.sy.musicapp.ui.search.SearchScreen
import com.sy.musicapp.ui.splash.SplashScreen
import com.sy.musicapp.ui.theme.Global
import com.sy.musicapp.ui.theme.MusicAppTheme
import kotlinx.coroutines.delay


@ExperimentalComposeUiApi
class MainActivity : ComponentActivity() {
    private var musicIntent: Intent? = null
    private lateinit var userModel: UserInfoViewModel
    private lateinit var searchModel: SearchViewModel
    private lateinit var playlistModel: PlaylistViewModel
    private lateinit var musicModel: MusicViewModel
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            val musicBinder = p1 as MediaPlayerService.MusicBinder
            musicModel.setMusicBinder(musicBinder)
            MyApplication.connection = this
        }

        override fun onServiceDisconnected(p0: ComponentName?) {}
    }

    @OptIn(ExperimentalAnimationApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        userModel = createModel(this)
        searchModel = createModel(this)
        playlistModel = createModel(this)
        musicModel = createModel(this)
        Util.showLog("onCreate")
        WindowCompat.setDecorFitsSystemWindows(window, false)
        setContent {
            MusicAppTheme {
                ProvideWindowInsets {
                    val navController = rememberNavController()
                    val systemUiController = rememberSystemUiController()
                    systemUiController.setSystemBarsColor(Global.colors.background)
                    systemUiController.systemBarsDarkContentEnabled = Global.colors.isLight
                    Scaffold(
                        backgroundColor = Global.colors.background,
                        modifier = Modifier
                            .fillMaxSize(1f)
                            .systemBarsPadding(),
                        bottomBar = {
                            Box(modifier = Modifier.padding(25.dp, 20.dp)) {
                                LittlePlayControl(
                                    musicModel = musicModel,
                                    onClick = {
                                        if (musicModel.currentMusic.value != Music.Empty)
                                            navController.navigate(Screen.Play)
                                    }
                                )
                            }
                        }
                    ) {
                        MainContent(navController = navController)
                    }
                    MusicListDrawer(musicModel)
                }
            }
        }

    }

    @ExperimentalComposeUiApi
    @ExperimentalAnimationApi
    @Composable
    fun MainContent(navController: NavHostController) {
        NavHost(
            navController = navController,
            startDestination = Screen.Splash.route
        ) {
            composable(Screen.Splash.route) {
                navController.enableOnBackPressed(false)
                musicModel.currentNavName = Screen.Splash.route
                SplashScreen()
                var loginState: Boolean? by remember {
                    mutableStateOf(null)
                }
                LaunchedEffect(true) {
                    userModel.updateStatus {
                        if (it) userModel.getUserInfo()
                        loginState = it
                    }
                }
                LaunchedEffect(loginState) {
                    delay(3000)
                    if (loginState !== null) {
                        if (loginState as Boolean) navController.navigate(Screen.Home)
                        else navController.navigate(Screen.Login)
                    }
                }
            }

            composable(Screen.Login.route) {
                //禁止按下返回键被Navigation处理进入回退栈
                navController.enableOnBackPressed(false)
                musicModel.currentNavName = Screen.Login.route
                NavEnterAndExitAnimation {
                    LoginScreen(
                        onSend = { username, pwd ->
                            userModel.login(username.trim(), pwd.trim(), callback =
                            object : UserInfoViewModel.LoginCallback {
                                override fun sucess() {
                                    navController.navigate(Screen.Home)
                                }

                                override fun failed() {
                                    "登陆失败".showToast()
                                }
                            }
                            )
                        }
                    )
                }
            }

            composable(Screen.Home.route) {
                navController.enableOnBackPressed(false)
                musicModel.currentNavName = Screen.Home.route
                NavEnterAndExitAnimation {
                    Box(modifier = Modifier.padding(25.dp, 20.dp)) {
                        HomeScreen(
                            navController = navController,
                            userModel = userModel,
                            searchModel = searchModel,
                            playlistModel = playlistModel,
                            musicModel = musicModel
                        )
                    }
                }
            }
            composable(Screen.Search.route + "/{searchKey}") {
                navController.enableOnBackPressed(true)
                musicModel.currentNavName = Screen.Search.route
                val key = it.arguments?.getString("searchKey")
                NavEnterAndExitAnimation {
                    Box(modifier = Modifier.padding(25.dp, 20.dp)) {
                        val searchResultList by searchModel.searchResultList.collectAsState()
                        SearchScreen(
                            navController,
                            key ?: "",
                            searchResultList,
                            musicModel,
                            onItemClick = { index ->
                                musicModel.addAllToMusicList(searchResultList)
                                musicModel.start(index)
                            },
                            onItemAddNext = { item ->
                                musicModel.addNextToMusicList(item)
                            }
                        )
                    }
                }
            }
            composable(Screen.Play.route) {
                navController.enableOnBackPressed(true)
                musicModel.currentNavName = Screen.Play.route
                NavEnterAndExitAnimation {
                    PlayScreen(musicModel)
                }
            }
            composable(Screen.Playlist.route + "/{playlist}") {
                navController.enableOnBackPressed(true)
                musicModel.currentNavName = Screen.Playlist.route
                val key = it.arguments?.getString("playlist")
                NavEnterAndExitAnimation {
                    Box(modifier = Modifier.padding(25.dp, 20.dp)) {
                        val playlistMusics by playlistModel.playlistMusics.collectAsState()
                        PlaylistScreen(
                            key = key ?: "",
                            navController = navController,
                            playlistMusics,
                            musicModel,
                            onItemClick = { index ->
                                musicModel.addAllToMusicList(playlistMusics)
                                musicModel.start(index)
                            },
                            onItemAddNext = { item ->
                                musicModel.addNextToMusicList(item)
                            }
                        )
                    }
                }
            }
        }
    }


    override fun onResume() {
        super.onResume()
        Util.showLog("onResume")
        //bind service
        if (musicIntent == null) {
            musicIntent = MyIntent<MediaPlayerService>(this)
            bindService(musicIntent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onBackPressed() {
        if (musicModel.isMusicListShow.value) {
            musicModel.musicListShowChange()
        } else {
            val exclude = listOf(Screen.Home.route, Screen.Splash.route, Screen.Login.route)
            if (exclude.contains(musicModel.currentNavName))
                moveTaskToBack(true) //可以阻止调用destroy方法，避免Activity销毁导致service结束
            else
                super.onBackPressed()
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        Util.showLog("onDestroy")
    }
}